import time
import re
from common.pre_config_brower import chrome_brower, request_for_sales
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Potterybarn:
    def __init__(self, url):
        self.driver = chrome_brower(disableIMG=True, disableJS=False)
        self.home_url = url
        self.main_windows_id = None
        self.open_web()

    # open the web pages
    def open_web(self):
        try:
            self.driver.get(self.home_url)
            self.driver.implicitly_wait(30)
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page(self):
        self.close_sticky()
        self.get_all_items()
        items_num_info_list = self.driver.find_elements_by_css_selector(
            "[data-component='Shop-ProductCell']")
        total_num = len(items_num_info_list)
        print("Total： %s" % total_num)
        for index, item in enumerate(items_num_info_list):
            produce_element = item.find_element_by_xpath('div/a')
            produce_url = produce_element.get_attribute("href")
            img_name_element = produce_element.find_element_by_xpath('img')
            jpg_url = img_name_element.get_attribute(
                "data-srcset").strip().split(" ")[0]
            produce_name = img_name_element.get_attribute("alt")
            price_element = item.find_elements_by_css_selector(
                "[class='product-price']")

            price_list = None
            if price_element:
                price_html = price_element[0].get_attribute('innerHTML')
                price_list = re.findall('"amount">(.*?)</span', price_html)

            if price_list:
                price_value = "$" + price_list[0]
            else:
                print("WARING: couldn't get price !!")
                price_value = "Not FOUND"
            print("%s/%s done !!" % (index, total_num))
            # print(jpg_url, produce_name, price_value, produce_url)
            yield jpg_url, produce_name, price_value, produce_url

    def get_all_items(self):
        while True:
            get_more_elements = self.driver.find_elements_by_css_selector(
                "[class='infinite-loading-container']")
            if get_more_elements:
                self.roll_to_top(get_more_elements[0])
                continue
            elif self.show_me_more():
                continue
            else:
                break

    def roll_to_top(self, target_element=None):
        top_down = "var q=document.documentElement.scrollTop=10000"
        to_element = "arguments[0].scrollIntoView();"

        if target_element:
            self.driver.execute_script(to_element, target_element)
            time.sleep(2)
        else:
            self.driver.execute_script(top_down)
        self.driver.implicitly_wait(30)

    def show_me_more(self):
        show_me_more = self.driver.find_elements_by_css_selector(
            "div.buttons.show-me-more > button")
        if show_me_more:
            show_me_more[0].click()
            self.driver.implicitly_wait(30)
            return True

    def close_sticky(self):
        sticky_elements = self.driver.find_elements_by_css_selector(
            "[class='stickyOverlayMinimizeButton']")
        btnClose_elements = self.driver.find_elements_by_css_selector(
            "[class='btnClose']")

        try:
            if sticky_elements:
                sticky_elements[0].click()
        except Exception as e:
            print(e)
            print("close sticky fail by class='stickyOverlayMinimizeButton'")

        try:
            if btnClose_elements:
                btn_num = len(btnClose_elements)
                btnClose_elements[btn_num - 1].click()
        except Exception as e:
            print(e)
            print("close sticky fail by class='btnClose' ", btn_num)
